package com.spdd.mt.task;

import cn.hutool.core.util.StrUtil;
import com.spdd.mt.biz.config.ConfigBean;
import com.spdd.mt.biz.constant.Operator;
import com.spdd.mt.biz.manager.feishu.FeiShuService;
import com.spdd.mt.biz.service.MtRechargeOrderService;
import com.spdd.mt.biz.vo.StatisticRechargeBean;
import com.spdd.mt.common.util.DateUtils;
import com.spdd.mt.common.util.MoneyUtil;
import com.spdd.mt.config.ScheduledCondition;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Conditional;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Slf4j
@Component
@Conditional(ScheduledCondition.class)
public class StatisticsTask {

    @Autowired
    private MtRechargeOrderService rechargeOrderService;

    @Autowired
    private ConfigBean configBean;

    @Autowired
    private FeiShuService feiShuService;

    /**
     * 每天早上6点执行
     */
    @Scheduled(cron = "0 0 6 * * ?")
    public void dyStatistic() {
        qualityStatistics("");
    }

    public void qualityStatistics(String lastDay) {
        LocalDate today = LocalDate.now();
        if (StrUtil.isBlank(lastDay)) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
            lastDay = today.minusDays(1).format(formatter);
        }
        log.info("开始执行统计任务，日期:{}", lastDay);
        try {
            String month = DateUtils.getCurrentMonth();
            LocalDate firstDayOfMonth = today.withDayOfMonth(1);
            if (today.isEqual(firstDayOfMonth)) {
                log.info("月初第一天，取上一月数据");
                month = DateUtils.getLastMonth();
            }
            for (String appId : configBean.getAppIds()) {
                StringBuilder content = new StringBuilder();
                content.append(lastDay).append("日各运营商成功的总笔数、总金额信息：").append("\n");
                List<StatisticRechargeBean> succList = rechargeOrderService.getSuccessStatistic(month, lastDay, appId);
                succList.forEach(s ->
                        content.append(StrUtil.blankToDefault(Operator.getNameByValue(s.getOperator()), "未知"))
                                .append(" - - ")
                                .append(MoneyUtil.fenToYuan(s.getFacePrice())).append(":")
                                .append(s.getTotalNum()).append("笔, ")
                                .append(MoneyUtil.fenToYuan(s.getTotalAmt().toString())).append("元。")
                                .append("\n")
                );
                content.append("\n\n\n");
                List<StatisticRechargeBean> twoList = rechargeOrderService.getRateStatistic(month, lastDay, 120, appId);
                List<StatisticRechargeBean> fiveList = rechargeOrderService.getRateStatistic(month, lastDay, 300, appId);
                Map<String, Integer> twoMap = twoList.stream()
                        .collect(Collectors.toMap(
                                s -> s.getOperator() + "-" + s.getFacePrice(),
                                StatisticRechargeBean::getTotalNum,
                                (oldValue, newValue) -> oldValue,
                                HashMap::new
                        ));
                Map<String, Integer> fiveMap = fiveList.stream()
                        .collect(Collectors.toMap(
                                s -> s.getOperator() + "-" + s.getFacePrice(),
                                StatisticRechargeBean::getTotalNum,
                                (oldValue, newValue) -> oldValue,
                                HashMap::new
                        ));

                List<StatisticRechargeBean> totalList = rechargeOrderService.getTotalStatistic(month, lastDay, appId);
                content.append(lastDay).append("日各运营商2分钟到账率信息：").append("\n");
                totalList.forEach(s ->
                        content.append(StrUtil.blankToDefault(Operator.getNameByValue(s.getOperator()), "未知"))
                                .append(" - - ")
                                .append(MoneyUtil.fenToYuan(s.getFacePrice())).append(":")
                                .append("2分钟内到账").append(twoMap.getOrDefault(s.getOperator() + "-" + s.getFacePrice(), 0)).append("笔, ")
                                .append("总笔数").append(s.getTotalNum()).append("笔, ")
                                .append("2分钟到账率:")
                                .append(BigDecimal.valueOf(twoMap.getOrDefault(s.getOperator() + "-" + s.getFacePrice(), 0)).multiply(BigDecimal.valueOf(100)).divide(BigDecimal.valueOf(s.getTotalNum()), 3, RoundingMode.HALF_UP)).append("%")
                                .append("\n")
                );
                content.append("\n\n\n");

                content.append(lastDay).append("日各运营商5分钟到账率信息：").append("\n");

                totalList.forEach(s ->
                        content.append(StrUtil.blankToDefault(Operator.getNameByValue(s.getOperator()), "未知"))
                                .append(" - - ")
                                .append(MoneyUtil.fenToYuan(s.getFacePrice())).append(":")
                                .append("5分钟内到账").append(fiveMap.getOrDefault(s.getOperator() + "-" + s.getFacePrice(), 0)).append("笔, ")
                                .append("总笔数").append(s.getTotalNum()).append("笔, ")
                                .append("5分钟到账率:")
                                .append(BigDecimal.valueOf(fiveMap.getOrDefault(s.getOperator() + "-" + s.getFacePrice(), 0)).multiply(BigDecimal.valueOf(100)).divide(BigDecimal.valueOf(s.getTotalNum()), 3, RoundingMode.HALF_UP)).append("%")
                                .append("\n")
                );

                Path directoryPath = Paths.get(configBean.getStatisticFilePath(), lastDay);
                Path filePath = directoryPath.resolve(appId + "-" + lastDay + ".txt");
                try {
                    Files.createDirectories(directoryPath);
                    Files.write(filePath, content.toString().getBytes(StandardCharsets.UTF_8));
                } catch (IOException ie) {
                    feiShuService.sendExceptionMsg(ie);
                    log.error("写入文件失败", ie);
                }
            }

        } catch (Exception e) {
            feiShuService.sendExceptionMsg(e);
            log.error("统计异常", e);
        }
        log.info("统计{}的数据任务结束", lastDay);
    }

}
